import { message } from 'antd';
import { useModel } from 'umi';
import StorageManager from '@/utils/StorageManager';
import { sortBy } from 'lodash';
import { normalLogin, getAuthorization, crmLogin } from '@/services/login';
import {
  queryConfigInfo,
  queryOptionsBrandList,
  queryOptionsActivityGroupTypeList,
  queryOptionsKeys,
  queryOptionsChannelList,
  queryOptionsCouponTagList,
  queryOptionsBusinessTypeList,
  queryOptionsCouponUseCategoryList,
  queryOptionsRegionList,
  queryOptionsFilterTagList,
  queryOptionsExtandvalueInfoList,
  queryOptionsFinanceBrandList,
  queryOptionsRevenueTypeList,
  queryOptionsExtandvalueIdList,
  queryOptionsScenarioList,
  queryOptionsUsemarketingList,
  optionsSiteTagList,
} from '@/services/profile';

const enumList = [
  'LASTEST_TOP',
  'PACKAGE_LIMIT',
  'PRICE_LIMIT',
  'ORDER_LIMIT',
  'REUSAVLE_TYPE',
  'OFFER_RESET',
  'ZMTYPE',
  'STYPE',
];

const useLogin = () => {
  const { initialState, setInitialState } = useModel('@@initialState');

  // 获取proFile列表-常量值--开始
  //  场景
  const getOptionsScenarioList = async () => {
    const { code, data } = await queryOptionsScenarioList();
    if (code === 200 && data) {
      const OptionsScenarioList = [] as API.OptionsKeys[];
      data.forEach((item: API.OptionsScenarioListItem) => {
        OptionsScenarioList.push({
          label: item.scenarioName,
          value: item.scenarioId,
        });
      });
      return OptionsScenarioList;
    }
    return [];
  };
  // 产品ID扩展属性
  const getOptionsExtandvalueIdList = async () => {
    const { code, data } = await queryOptionsExtandvalueIdList();
    if (code === 200 && data) {
      const OptionsExtandvalueIdList = [] as API.OptionsKeys[];
      data.forEach((item: API.OptionsExtandvalueIdListItem) => {
        OptionsExtandvalueIdList.push({
          label: item.extandname,
          value: item.extandname,
        });
      });
      return OptionsExtandvalueIdList;
    }
    return [];
  };
  // 收入类型
  const getOptionsRevenueTypeList = async () => {
    const { code, data } = await queryOptionsRevenueTypeList();
    if (code === 200 && data) {
      const OptionsRevenueTypeList = [] as API.OptionsKeys[];
      data.forEach((item: API.OptionsRevenueTypeListItem) => {
        OptionsRevenueTypeList.push({
          label: item.revenueType,
          value: item.revenueType,
        });
      });
      return OptionsRevenueTypeList;
    }
    return [];
  };
  // 余额归属品牌
  const getOptionsFinanceBrandList = async () => {
    const { code, data } = await queryOptionsFinanceBrandList();
    if (code === 200 && data) {
      const OptionsFinanceBrandList = [] as API.OptionsKeys[];
      data.forEach((item: API.OptionsFinanceBrandListItem) => {
        OptionsFinanceBrandList.push({
          label: item.financeBrand,
          value: item.financeBrand,
        });
      });
      return OptionsFinanceBrandList;
    }
    return [];
  };
  // 扩展属性
  const getOptionsExtandvalueInfoList = async () => {
    const { code, data } = await queryOptionsExtandvalueInfoList();
    if (code === 200 && data) {
      const OptionsExtandvalueInfoList = [] as API.OptionsKeys[];
      data.forEach((item: API.OptionsExtandvalueInfoListItem) => {
        OptionsExtandvalueInfoList.push({
          label: item.extandName,
          value: item.extandName,
          type: item.type,
        });
      });
      return OptionsExtandvalueInfoList;
    }
    return [];
  };
  // 券过滤标签
  const getOptionsFilterTagList = async () => {
    const { code, data } = await queryOptionsFilterTagList();
    if (code === 200 && data) {
      const OptionsFilterTagList = [] as API.OptionsKeys[];
      data.forEach((item: API.OptionsFilterTagListItem) => {
        OptionsFilterTagList.push({
          label: item.filterTag,
          value: item.filterTag,
        });
      });
      return OptionsFilterTagList;
    }
    return [];
  };
  // 区域
  const getOptionsRegionList = async () => {
    const { code, data } = await queryOptionsRegionList();
    if (code === 200 && data) {
      const OptionsRegionList = [] as API.OptionsKeys[];
      data.forEach((item: API.OptionsRegionListItem) => {
        OptionsRegionList.push({
          label: item.regionName,
          value: item.regionName,
        });
      });
      return OptionsRegionList;
    }
    return [];
  };
  // 券码用途
  const getOptionsCouponUseCategoryList = async () => {
    const { code, data } = await queryOptionsCouponUseCategoryList();
    if (code === 200 && data) {
      const OptionsCouponUseCategoryList = [] as API.OptionsKeys[];
      data.forEach((item: API.OptionsCouponUseCategoryListItem) => {
        OptionsCouponUseCategoryList.push({
          label: item.usecate,
          value: item.usecate,
        });
      });
      return OptionsCouponUseCategoryList;
    }
    return [];
  };
  // 业务类型
  const getOptionsBusinessTypeList = async () => {
    const { code, data } = await queryOptionsBusinessTypeList();
    if (code === 200 && data) {
      const OptionsBusinessTypeList = [] as API.OptionsKeys[];
      data.forEach((item: API.OptionsBusinessTypeListItem) => {
        OptionsBusinessTypeList.push({
          label: item.businessType,
          value: item.businessType,
        });
      });
      return OptionsBusinessTypeList;
    }
    return [];
  };
  // 券标签
  const getOptionsCouponTagList = async () => {
    const { code, data } = await queryOptionsCouponTagList();
    if (code === 200 && data) {
      const OptionsCouponTagList = [] as API.OptionsKeys[];
      data.forEach((item: API.OptionsCouponTagListItem) => {
        OptionsCouponTagList.push({
          label: item.tagName,
          value: item.tagName,
          tagvalue: item.tagValue,
        });
      });
      return OptionsCouponTagList;
    }
    return [];
  };
  // 渠道查询
  const getOptionsChannelList = async () => {
    const { code, data } = await queryOptionsChannelList();
    if (code === 200 && data) {
      const OptionsChannelList = [] as API.OptionsKeys[];
      data.forEach((item: API.OptionsChannelListItem) => {
        OptionsChannelList.push({
          label: item.channelId + '-' + item.channelName,
          value: item.channelId,
        });
      });
      return OptionsChannelList;
    }
    return [];
  };
  // 常量--枚举值
  const getOptionsKeys = async () => {
    const { code, data } = await queryOptionsKeys({
      key: enumList,
    });
    if (code === 200 && data) {
      const LASTESTTOP = [] as API.OptionsKeys[];
      const PACKAGELIMIT = [] as API.OptionsKeys[];
      const PRICELIMIT = [] as API.OptionsKeys[];
      const ORDERLIMIT = [] as API.OptionsKeys[];
      const REUSAVLETYPE = [] as API.OptionsKeys[];
      const OFFERRESET = [] as API.OptionsKeys[];
      const ZMTYPE = [] as API.OptionsKeys[];
      const STYPE = [] as API.OptionsKeys[];

      data.forEach((item: API.OptionsKeysItem) => {
        switch (item.key) {
          case 'LASTEST_TOP':
            LASTESTTOP.push({
              label: item.value + '-' + item.name,
              value: Number(item.value),
            });
            break;
          case 'PACKAGE_LIMIT':
            PACKAGELIMIT.push({
              label: item.value + '-' + item.name,
              value: item.value,
            });
            break;
          case 'PRICE_LIMIT':
            PRICELIMIT.push({
              label: item.value + '-' + item.name,
              value: item.value,
            });
            break;
          case 'ORDER_LIMIT':
            ORDERLIMIT.push({
              label: item.value + '-' + item.name,
              value: item.value,
            });
            break;
          case 'REUSAVLE_TYPE':
            REUSAVLETYPE.push({
              label: item.name,
              value: item.value,
            });
            break;
          case 'OFFER_RESET':
            OFFERRESET.push({
              label: item.value + '-' + item.name,
              value: Number(item.value),
            });
            break;
          case 'ZMTYPE':
            ZMTYPE.push({
              label: item.name,
              value: item.value,
            });
            break;
          case 'STYPE':
            STYPE.push({
              label: item.name,
              value: item.value,
            });
            break;
        }
      });

      const obj = {
        LASTESTTOP: sortBy(LASTESTTOP, 'value'),
        PACKAGELIMIT: sortBy(PACKAGELIMIT, 'value'),
        PRICELIMIT: PRICELIMIT,
        ORDERLIMIT: sortBy(ORDERLIMIT, 'value'),
        REUSAVLETYPE: REUSAVLETYPE,
        OFFERRESET: OFFERRESET,
        ZMTYPE: ZMTYPE,
        STYPE: STYPE,
      };

      return obj;
    }
    return {
      LASTESTTOP: [],
      PACKAGELIMIT: [],
      PRICELIMIT: [],
      ORDERLIMIT: [],
      REUSAVLETYPE: [],
      OFFERRESET: [],
      ZMTYPE: [],
      STYPE: [],
    };
  };
  // 活动组列表
  const getOptionsActivityGroupTypeList = async () => {
    const { code, data } = await queryOptionsActivityGroupTypeList();
    if (code === 200 && data) {
      const OptionsActivityGroupTypeListBro = [] as API.OptionsKeys[];
      data.forEach((item: API.OptionsActivityGroupTypeListItem) => {
        OptionsActivityGroupTypeListBro.push({
          label: item.groupType,
          value: item.id,
        });
      });
      return OptionsActivityGroupTypeListBro;
    }
    return [];
  };
  // 品牌列表
  const getOptionsBrandList = async () => {
    const { data, code } = await queryOptionsBrandList();
    if (code === 200 && data) {
      const OptionsBrandList = [] as API.OptionsKeys[];
      const OptionsPlaceBrandList = [] as API.OptionsKeys[];
      data.forEach((item: API.OptionsBrandListItem) => {
        OptionsBrandList.push({
          label: item.brandName,
          value: item.brandId,
        });
      });
      data.forEach((item: API.OptionsBrandListItem) => {
        OptionsPlaceBrandList.push({
          label: item.brandId + '-' + item.brandName,
          value: item.brandId,
        });
      });

      return [OptionsBrandList, OptionsPlaceBrandList];
    }
    return [[], []];
  };

  const getOptionsUsemarketingList = async () => {
    const { data, code } = await queryOptionsUsemarketingList({ type: 2 });
    if (code === 200) {
      const arrTwo = [] as API.OptionsKeys[];
      data?.forEach((item: API.OptionsUsemarketingListItem) => {
        // if (item.type === 1) {
        //   arrOne.push({
        //     label: item.ruleName,
        //     value: item.rule,
        //   });
        // }
        if (item.type === 2) {
          arrTwo.push({
            label: item.ruleName,
            value: item.rule,
          });
        }
      });

      return arrTwo;
    }
    return [];
  };

  const getOptionsSiteTagList = async () => {
    const { data, code } = await optionsSiteTagList({});
    if (code === 200) {
      const arrTwo = [] as API.OptionsKeys[];
      data?.forEach((item: API.OptionsUsemarketingListItem) => {
        arrTwo.push({
          label: item,
          value: item,
        });
      });

      return arrTwo;
    }
    return [];
  };

  // 获取proFile列表-常量值--结束

  /**
   * 获取proFile列表-常量值
   */
  const getEunmList = async () => {
    const arrBrandList = await getOptionsBrandList();
    const keysConstObj = await getOptionsKeys();

    const eunmList = {
      OptionsBrandList: arrBrandList[0],
      OptionsPlaceBrandList: arrBrandList[1],
      LASTESTTOP: keysConstObj.LASTESTTOP,
      PACKAGELIMIT: keysConstObj.PACKAGELIMIT,
      PRICELIMIT: keysConstObj.PRICELIMIT,
      ORDERLIMIT: keysConstObj.ORDERLIMIT,
      REUSAVLETYPE: keysConstObj.REUSAVLETYPE,
      OFFERRESET: keysConstObj.OFFERRESET,
      ZMTYPE: keysConstObj.ZMTYPE,
      STYPE: keysConstObj.STYPE,
      OptionsActivityGroupTypeListBro: await getOptionsActivityGroupTypeList(),
      OptionsChannelList: await getOptionsChannelList(),
      OptionsCouponTagList: await getOptionsCouponTagList(),
      OptionsBusinessTypeList: await getOptionsBusinessTypeList(),
      OptionsCouponUseCategoryList: await getOptionsCouponUseCategoryList(),
      OptionsRegionList: await getOptionsRegionList(),
      OptionsFilterTagList: await getOptionsFilterTagList(),
      OptionsExtandvalueInfoList: await getOptionsExtandvalueInfoList(),
      OptionsFinanceBrandList: await getOptionsFinanceBrandList(),
      OptionsRevenueTypeList: await getOptionsRevenueTypeList(),
      OptionsExtandvalueIdList: await getOptionsExtandvalueIdList(),
      OptionsScenarioList: await getOptionsScenarioList(),
      OptionsUsemarketingMore: await getOptionsUsemarketingList(),
      OptionsSiteTagList: await getOptionsSiteTagList(),
    };

    StorageManager.setLocalStorageSync('eunmList', eunmList);
  };

  /**
   * 权限查询
   */
  const queryAuthorization = async () => {
    const { data, code } = await getAuthorization();
    if (code === 200 && data) {
      return data;
    }
    return [];
  };

  /**
   * 获取配置信息
   */
  const getConfigInfo = async () => {
    const { data, code } = await queryConfigInfo({ key: 'allowPersonalLimitCount' });
    if (code === 200 && data) {
      return data;
    }
    return '';
  };

  /**
   * 登录完成
   * @param msg
   */
  const afterLogin = async (msg: API.TResult<API.LoginInfo>, values: API.LoginParams) => {
    const currentUserInfo: API.LoginInfo = msg.data || ({} as API.LoginInfo);
    StorageManager.setLocalStorageSync('token', currentUserInfo.token);
    // 这里接口需要token
    // const useInfo = await getUserInfo(currentUserInfo.user.id);
    // currentUserInfo.user = {
    //   ...currentUserInfo.user,
    //   ...useInfo,
    // }
    // 查询用户权限
    const authorization: API.AuthorizationItem[] = await queryAuthorization();
    const configInfo: string = await getConfigInfo();
    currentUserInfo.username = values.username;
    StorageManager.setLocalStorageSync('current-user', currentUserInfo);
    StorageManager.setLocalStorageSync('authorization', authorization);
    StorageManager.setLocalStorageSync('configInfo', configInfo);
    setInitialState({
      ...initialState,
      currentUser: currentUserInfo,
      authorization: authorization,
      configInfo: configInfo,
    });
    // 获取常量
    getEunmList();
  };

  /**
   * 正常登录
   * @param values
   * @returns
   */
  const login = async (values: API.LoginParams) => {
    try {
      const msg = await normalLogin(values);
      if (msg.code === 200 && msg.data) {
        message.success('登录成功！');
        await afterLogin(msg, values);
        return true;
      }
      return false;
    } catch (error) {
      console.log(error);
      return false;
    }
  };

  /**
   * CRM登录
   * @param param0
   * @returns
   */
  const CRMLogin = async ({ ticket = '' }) => {
    try {
      const msg = await crmLogin({
        ticket: ticket || '',
      });
      if (msg.code === 200 && msg.data) {
        const values: any = {
          username: msg.data.username,
        };
        // message.success('登录成功！');
        await afterLogin(msg, values);
        return true;
      }
      return false;
    } catch (error) {
      return false;
    }
  };

  return {
    login,
    CRMLogin,
  };
};

export default useLogin;
